<?php

namespace app\beautiful\controller\admin\mall\order;

use app\BaseController;

use app\beautiful\model\LevelModel;
use app\beautiful\model\order\PinTuanOrderModel;
use app\common\logic\DataLogic;

use app\common\logic\SmsLogic;

use app\beautiful\logic\printer\PrinterLogic;

use app\beautiful\model\member\MemberModel;

use app\beautiful\model\order\GoodsOrderItemModel;

use app\beautiful\model\order\GoodsOrderModel;

use app\beautiful\model\setting\SettingSmsModel;



class Order extends BaseController{

    public function getGoodsOrderNum()

    {

        $order_num=GoodsOrderModel::where([

                ['shop_id','=',$this->request->shopId],

                ['is_delete','=',0],

                ['status','in',[2,4,9]]

            ])->count() ?? 0;

        return $this->success(['order_num'=>$order_num]);

    }

    /*产品订单*/
    public function index()

    {
        $order_type = $this->request->param('order_type');

        $search_type = $this->request->param('search_type');//1订单编号2项目名称

        $search = $this->request->param('search/d',1);

        $status = $this->request->param('status/d',0);

        $time_type = $this->request->param('time_type/d',-1);//0今日1昨日2本周3本月

        $start_time = $this->request->param('start_time');

        $end_time = $this->request->param('end_time');
        switch ($time_type){

            case 0:

                $start_time = date("Y-m-d H:i:s",strtotime("today"));

                $end_time = date("Y-m-d H:i:s",strtotime("today")+86399);

                break;

            case 1:

                $start_time = date('Y-m-d',mktime(0,0,0,date('m'),date('d')-1,date('Y')));

                $end_time = date("Y-m-d H:i:s",strtotime("today")-1);

                break;

            case 2:

                $start_time = date("Y-m-d H:i:s",mktime(0, 0 , 0,date("m"),date("d")-date("w")+1,date("Y")));

                $end_time = date("Y-m-d H:i:s",mktime(23,59,59,date("m"),date("d")-date("w")+7,date("Y")));

                break;

            case 3:

                $start_time = date("Y-m-d H:i:s",mktime(0, 0 , 0,date("m"),1,date("Y")));

                $end_time = date("Y-m-d H:i:s",mktime(23,59,59,date("m"),date("t"),date("Y")));

                break;

        }

        $where = [

            ['shop_id','=',$this->request->shopId],

            ['is_delete','=',0]
        ];
        if(!empty($start_time) && !empty($end_time)){
            $where[] = ['add_time','between',[strtotime($start_time),strtotime($end_time)]];
        }
        //包含产品的订单id
        $pc_order_ids = $this->orderIds(['ot.shop_id'=>$this->request->shopId,'g.type'=>2]);
        $where[] = ['order_id','in',$pc_order_ids];
        if(!empty($status)) $where[] = ['status','=',$status];
        if(!empty($order_type)) $where[] = ['order_type','=',$order_type];
        if(!empty($search)){
            if($search_type==1){
                $where[] = ['order_id','like','%'.$search.'%'];
            }
            if($search_type==2){
                $s_where = [
                    ['ot.shop_id','=',$this->request->shopId],
                    ['g.name','like','%'.$search.'%']
                ];
                $order_ids = $this->orderIds($s_where);
                $where[] = ['order_id','in',$order_ids];
            }
        }

        $order_model = new GoodsOrderModel();

        $order_model = $order_model->with(['skus','partner','member','partnerCommission','coupon']);

        $order = ['add_time'=>'desc'];

        $field = "*";

        $append = ['add_time_format','pay_time_format','status_means','order_type_means','pay_type_mean'];

        $return = DataLogic::getDataList($order_model,$where,$order,$field,$this->request->limit,$this->request->page,$append);


        //处理数据
        $lists = $return['list'];

        if(empty(!$lists)){
            foreach ($lists as $k => $list){
                if($list['order_send_time']) $lists[$k]['order_send_time'] = json_decode($list['order_send_time'],true);
                $commission = 0;
                foreach ($list['partnerCommission'] as $key=>$value){

                    $commission += $value['commission'];
                }
                unset($lists[$k]['partnerCommission']);
                //股东提成
                $lists[$k]['percentage'] = sprintf("%.2f",$commission);
                //商家实收
                $lists[$k]['boss_real_receive'] = sprintf("%.2f",$list['need_pay'] - $list['freight'] - $commission - $list['coupon_money']);
                //股东身份
                $partner_role_name = '未知';
                if($list['partner']){
                    if($list['partner']['role_id']==1){
                        $partner_role_name = '股东';
                    }
                    if($list['partner']['role_id']==2){
                        $partner_role_name = '员工';
                    }
                    if($list['partner']['role_id']==3){
                        $partner_role_name = '会员';
                    }
                    if($list['partner']['role_id']==4){
                        $partner_role_name = '自定义';
                    }
                    if($list['partner']['role_id']==5){
                        $partner_role_name = '投资合伙人';
                    }
                    if($list['partner']['role_id']==6){
                        $partner_role_name = '储值合伙人';
                    }
                }
                $lists[$k]['partner_role_name'] = $partner_role_name;
                $lists[$k]['level'] = LevelModel::where(['shop_id'=>$this->request->shopId,'is_delete'=>0,'level_id'=>$list['member']['level_id']])->value('name');
                $lists[$k]['nick_name'] = $list['member']['nick_name'];
                $lists[$k]['mobile'] = $list['member']['mobile'];
                $lists[$k]['face'] = $list['member']['face'];
                $lists[$k]['coupon_name'] = $list['coupon']?$list['coupon']['name']:null;

                $order_goods_info = $this->orderGoodsInfos(['shop_id'=>$this->request->shopId,'order_id'=>$list['order_id']]);
                $lists[$k]['goods_name'] = $order_goods_info['goods_name'];
                $lists[$k]['goods_num'] = $order_goods_info['goods_num'];
                $lists[$k]['goods_original_price'] = $order_goods_info['goods_original_price'];
                $lists[$k]['goods_price'] = $order_goods_info['goods_price'];
                unset($lists[$k]['partner']);
                unset($lists[$k]['member']);
                unset($lists[$k]['coupon']);
            }
        }


        $return['list']=$lists;

        return $this->success($return);



    }
    /*套餐订单*/
    public function packageIndex()

    {


    }
    /*获取订单id*/
    public function orderIds($where){
        //包含产品的订单id
        $order_item = GoodsOrderItemModel::alias('ot')
            ->leftJoin('beautiful_goods g','ot.goods_id=g.goods_id')
            ->field('ot.*')
            ->where($where)
            ->select()->toArray();
        if(empty($order_item)){
            return [];
        }
        $order_ids = array_column($order_item, 'order_id');
        return $order_ids;
    }

    /*获取子订单产品*/
    public function orderGoodsInfos($where){
        $goods_name = '';
        $goods_num = 0;
        $goods_original_price = $goods_price = 0;
        $order_item = GoodsOrderItemModel::with(['goods'])->where($where)->select()->toArray();
        foreach ($order_item as $k=>$v){
            if($v['goods']){
                $goods_name .=$v['goods']['name'].'、';
            }
            $goods_num += $v['goods_num'];
            $goods_original_price += $v['goods_original_price'];
            $goods_price += $v['goods_price'];
            $discount[]=[
                'vip_discount_type'=>$v['vip_discount_type'],
                'discount_detail'=>$v['discount_detail'],
            ];
        }
        $return = [
            'goods_name'=>rtrim($goods_name,'、'),
            'goods_num'=>$goods_num,
            'goods_original_price'=>$goods_original_price,
            'goods_price'=>$goods_price
        ];
        return $return;
    }
    /*订单详情*/
    public function detail()

    {

        $order_id = $this->request->param('order_id/d',0);

        if($order_id==0) return $this->error('订单不存在#1');

        $order_model = new GoodsOrderModel();

        $order_model = $order_model->with(['partnerCommission','partner']);


        if(null === $order = $order_model->where(['order_id'=>$order_id])->json(['order_send_time'],true)->find()) return $this->error('订单不存在#2');

        if($order->shop_id != $this->request->shopId) return $this->error('订单不存在#3');

        if($order->is_delete != 0) return $this->error('订单不存在#4');



        if(null === $member = MemberModel::find($order->member_id)) return $this->error('订单不存在#5');

        if($member->shop_id != $this->request->shopId) return $this->error('订单不存在#6');



        $items=GoodsOrderItemModel::where([

            ['shop_id','=',$this->request->shopId],

            ['order_id','=',$order_id]

        ])->select()->toArray();

        if(empty($items)) return $this->error('订单不存在#7');



        $order->append(['add_time_format','pay_time_format','status_means','order_type_means','pay_type_mean']);

        $commission = 0;

        foreach ($order->partnerCommission as $key=>$value){

            $commission += $value['commission'];
        }

        //股东提成
        $percentage = $commission;
        //商家实收
        $boss_real_receive = $order->need_pay - $order->freight - $commission - $order->coupon_money;

        $partner_role_name = '未知';

        if($order['partner']){
            if($order['partner']['role_id']==1){
                $partner_role_name = '股东';
            }
            if($order['partner']['role_id']==2){
                $partner_role_name = '员工';
            }
            if($order['partner']['role_id']==3){
                $partner_role_name = '会员';
            }
            if($order['partner']['role_id']==4){
                $partner_role_name = '自定义';
            }
            if($order['partner']['role_id']==5){
                $partner_role_name = '投资合伙人';
            }
            if($order['partner']['role_id']==6){
                $partner_role_name = '储值合伙人';
            }
        }

        $detail=[

            'order_id'=>$order->order_id,

            'logistics_type'=>$order->logistics_type,

            'add_time_format'=>$order->add_time_format,

            'order_type_means'=>$order->order_type_means,

            'status'=>$order->status,

            'status_means'=>$order->status_means,

            'need_pay'=>$order->need_pay,

            'pay_type'=>$order->pay_type,

            'pay_type_mean'=>$order->pay_type_mean,

            'pay_time_format'=>$order->pay_time_format,

            'receiving_name'=>$order->receiving_name,

            'receiving_mobile'=>$order->receiving_mobile,

            'receiving_address_province'=>$order->receiving_address_province,

            'receiving_address_city'=>$order->receiving_address_city,

            'receiving_address_county'=>$order->receiving_address_county,

            'receiving_address_info'=>$order->receiving_address_info,

            'total_price'=>$order->total_price,

            'youhui_balance'=>$order->youhui_balance,

            'freight'=>$order->freight,

            'coupon_money'=>$order->coupon_money,

            'integral_balance'=>$order->integral_balance,

            'member_name'=>$member->nick_name,

            'member_mobile'=>$member->mobile,

            'member_face'=>$member->face,

            'items'=>$items,

            'order_send_time'=>$order->order_send_time,

            'percentage'=>sprintf("%.2f",$percentage),

            'boss_real_receive'=>sprintf("%.2f",$boss_real_receive),

            'partner_role_name'=>$partner_role_name,

            'level'=>LevelModel::where(['shop_id'=>$this->request->shopId,'is_delete'=>0,'level_id'=>$member->level_id])->value('name')

        ];



        return $this->success(['detail'=>$detail]);

    }


}

